package cn.edu.zafu.bigdata.linfeifei.I;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

public class UdpTimeServer {
    public static void main(String[] args) {
        int port = 1234; // 服务端端口号
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("UDP Time Server is running on port " + port);

            while (true) {
                byte[] receiveBuffer = new byte[1024];
                byte[] sendBuffer = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                socket.receive(receivePacket);

                String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Received: " + received);

                // 发送当前时间
                InetAddress address = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                GregorianCalendar now = new GregorianCalendar();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf.format(now.getTime());

                sendBuffer = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, address, clientPort);
                socket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
